<script lang="ts" setup>
import { reactive, ref, onMounted } from "vue";
import ServiceInfo from "./components/ServiceInfo.vue";
import SubServiceInfo from "./components/SubServiceInfo.vue";
import {
  getServicePage,
  createService,
  modifyService,
  createServiceOption,
  modifyServiceOption,
  delService
} from "/@/api/service";
import { ElMessage, ElMessageBox } from "element-plus";
import dayjs from "dayjs";
import { getUserList } from "/@/api/user";
import timezone from "dayjs/plugin/timezone";
import utc from "dayjs/plugin/utc";
dayjs.extend(utc);
dayjs.extend(timezone);

const tableData = ref([]);
const dialogVisible = ref<boolean>(false);
const subDialogVisible = ref<boolean>(false);
const title = ref<string>("");
const subTitle = ref<string>("");
const query = reactive({ user_nid: "", currentPage: 1, pageSize: 15 });
const total = ref(0);
const type = ref(1);
const subType = ref(1);
const formData = ref({
  name: "",
  currency_type: "USD",
  price: null,
  notes: ""
});
const subFormData = ref({
  service_id: "",
  name: "",
  value: "",
  price: null,
  notes: ""
});
const expands = ref([]);
const userList = ref([]);

onMounted(() => {
  getUserData();
});

const getUserData = () => {
  getUserList().then(({ data }) => {
    userList.value = data;
    query.user_nid = data[0].nid;
    getTableData();
  });
};

const addService = () => {
  type.value = 1;
  title.value = "添加服务";
  formData.value = {
    name: "",
    currency_type: "USD",
    price: null,
    notes: ""
  };
  dialogVisible.value = true;
};

const editServeci = row => {
  type.value = 2;
  title.value = "修改服务";
  formData.value = JSON.parse(JSON.stringify(row));
  dialogVisible.value = true;
};

const getTableData = () => {
  getServicePage(query).then((res: any) => {
    const obj: any = Object.values(res.data.data);
    obj.forEach(item => {
      item.price = Number(item.price);
    });
    tableData.value = obj;
    total.value = res.data.total;
  });
};

const handleSizeChange = val => {
  query.pageSize = val;
  getTableData();
};

const handleCurrentChange = val => {
  query.currentPage = val;
  getTableData();
};

const initFormData = () => {
  formData.value = {
    name: "",
    currency_type: "USD",
    price: null,
    notes: ""
  };
};

const initSubFormData = () => {
  subFormData.value = {
    service_id: "",
    name: "",
    value: "",
    price: null,
    notes: ""
  };
};

const submitForm = async val => {
  const asyncFn = type.value === 1 ? createService : modifyService;
  const obj = userList.value.find(item => item.nid === query.user_nid);
  const params = { ...val, user_nid: obj.nid, user_name: obj.name };
  await asyncFn(params);
  ElMessage({
    type: "success",
    message: "操作成功"
  });
  dialogVisible.value = false;
  getTableData();
};

const submitSubForm = async val => {
  const asyncFn =
    subType.value === 1 ? createServiceOption : modifyServiceOption;
  await asyncFn(val);
  ElMessage({
    type: "success",
    message: "操作成功"
  });
  subDialogVisible.value = false;
  getTableData();
};

const addSubService = id => {
  initSubFormData();
  subFormData.value.service_id = id;
  subDialogVisible.value = true;
  subType.value = 1;
  subTitle.value = "添加子服务";
};

const editSubService = val => {
  const obj = { ...val };
  obj.price = Number(obj.price);
  subFormData.value = obj;
  subDialogVisible.value = true;
  subType.value = 2;
  subTitle.value = "编辑子服务";
};

/** 展开行的回调 */
const expandChange = (row, expandList) => {
  expands.value = expandList.map(item => item.id);
};

const deleteServeci = async id => {
  ElMessageBox.confirm("是否确认删除", "Warning", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    await delService({ id });
    ElMessage({
      type: "success",
      message: "操作成功"
    });
    getTableData();
  });
};
</script>

<template>
  <div class="service-warp">
    <el-card>
      <el-button type="primary" @click="addService">添加服务</el-button>
      <span style="margin-left: 40px">客户: </span>
      <el-select v-model="query.user_nid" @change="getTableData">
        <el-option
          v-for="item in userList"
          :key="item.nid"
          :label="item.name"
          :value="item.nid"
        />
      </el-select>
      <el-table
        :data="tableData"
        stripe
        border
        style="width: 100%; margin-top: 20px"
        row-key="id"
        :expand-row-keys="expands"
        @expand-change="expandChange"
      >
        <el-table-column type="expand">
          <template #default="{ row }">
            <div class="sub-table">
              <el-table :data="row.service_option" size="small">
                <el-table-column prop="name" label="选项名" />
                <el-table-column prop="value" label="选项值" />
                <el-table-column prop="price" label="价格" />
                <el-table-column prop="notes" label="备注" />
                <el-table-column label="创建时间(加利福尼亚)">
                  <template #default="{ row }">
                    {{
                      row.created_at
                        ? dayjs(row.created_at * 1000)
                            .tz("America/Los_Angeles")
                            .format("YYYY-MM-DD HH:mm:ss")
                        : ""
                    }}
                  </template>
                </el-table-column>
                <el-table-column label="更新时间(加利福尼亚)">
                  <template #default="{ row }">
                    {{
                      row.updated_at
                        ? dayjs(row.updated_at * 1000)
                            .tz("America/Los_Angeles")
                            .format("YYYY-MM-DD HH:mm:ss")
                        : ""
                    }}
                  </template>
                </el-table-column>
                <el-table-column label="操作">
                  <template #default="{ row }">
                    <el-button
                      size="small"
                      @click="editSubService(row)"
                      type="primary"
                      >修改</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="服务名称" />
        <el-table-column prop="currency_type" label="币种" />
        <el-table-column prop="price" label="价格" />
        <el-table-column prop="notes" label="备注" />
        <el-table-column label="创建时间(加利福尼亚)">
          <template #default="{ row }">
            {{
              row.created_at
                ? dayjs(row.created_at * 1000)
                    .tz("America/Los_Angeles")
                    .format("YYYY-MM-DD HH:mm:ss")
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column label="更新时间(加利福尼亚)">
          <template #default="{ row }">
            {{
              row.updated_at
                ? dayjs(row.updated_at * 1000)
                    .tz("America/Los_Angeles")
                    .format("YYYY-MM-DD HH:mm:ss")
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template #default="{ row }">
            <el-button type="primary" @click="editServeci(row)" size="small"
              >修改</el-button
            >
            <el-button @click="deleteServeci(row.id)" size="small"
              >删除</el-button
            >
            <el-button
              size="small"
              @click="addSubService(row.id)"
              type="primary"
              >添加子选项</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div style="display: flex; justify-content: flex-end; margin-top: 10px">
        <el-pagination
          v-model:currentPage="query.currentPage"
          v-model:page-size="query.pageSize"
          :page-sizes="[5, 10, 15, 20, 30]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="Number(total)"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <service-info
      v-model="dialogVisible"
      :title="title"
      :type="type"
      :formData="formData"
      @init-form="initFormData"
      @submit-form="submitForm"
    />

    <sub-service-info
      v-model="subDialogVisible"
      :title="subTitle"
      :type="subType"
      :form-data="subFormData"
      @init-sub-form="initSubFormData"
      @submit-sub-form="submitSubForm"
    />
  </div>
</template>

<style lang="scss" scoped>
.sub-table {
  padding-left: 100px;
}
</style>
